package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.project.bean.SuppliersBean;
import com.project.service.ISuppliersService;
import com.project.valid.AddValid;
import com.project.valid.UpdateValid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@RequestMapping("supplier")
public class SupplierController {
        @Autowired
        private ISuppliersService service;
        @RequestMapping("findAll")
        public List<SuppliersBean> findAll(){
            return service.findAll();
        }
        @RequestMapping("findByItem")
        public PageInfo<SuppliersBean> findByItem(Integer pageNO, String name, String scope){
            return service.findByItem(pageNO, name, scope);
        }
        @RequestMapping("findById")
        public SuppliersBean findById(int id){
            return service.findById(id);
        }
        @RequestMapping("add")
        public String add(@Validated(AddValid.class) SuppliersBean suppliers, BindingResult result) throws JsonProcessingException {
            if(result.hasErrors()){
                return new ObjectMapper().writeValueAsString(result.getFieldErrors());
            }else {
                service.add(suppliers);
                return "ok";
            }
        }
        @RequestMapping("update")
        public String update(@Validated(UpdateValid.class) SuppliersBean suppliers, BindingResult result) throws JsonProcessingException {
            if(result.hasErrors()){
                    return new ObjectMapper().writeValueAsString(result.getFieldErrors());
            }else {
                service.update(suppliers.getId(), suppliers.getHeadMan(),suppliers.getTel() );
                return "ok";
            }

        }

    }
